package com.phpxiu.app.view.custom;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.LinearLayout;


import com.phpxiu.app.model.msg.CommonMsg;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by 吴金洲 on 2016/7/20
 */
public class FlyWordsView extends LinearLayout implements FlyWordView.FlyWordViewAnimEndListener{
    private final static int MAIN_HANDLE_FLY=0x5601;//飞出动画
    private final List<CommonMsg>flyWords=new ArrayList<CommonMsg>();
    public FlyWordView wordView1,wordView2;
    private FlyWordThread managerWordsThread=new FlyWordThread();
    private static Handler animMsgThreadHandler;
    private static Handler mHandler;
    public FlyWordsView(Context context) {
        super(context);
        init(context);
    }

    public FlyWordsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public FlyWordsView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @TargetApi(21)
    public FlyWordsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    /**
     * 初始化
     * @param context
     */
    private final void init(Context context){
        wordView1=new FlyWordView(context,1);
        wordView1.addAnimEndListener(this);
        wordView2=new FlyWordView(context,2);
        wordView2.addAnimEndListener(this);
        LayoutParams layoutParams=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,wordView1.getHeadHeight());
        addView(wordView1,layoutParams);
        addView(wordView2,layoutParams);
        mHandler=new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                CommonMsg word=(CommonMsg)msg.obj;
                if(1==word.getFlyIndex()){
                    wordView1.prepareFly(word.getFuser().getAvatar(),word.getFuser().getNickname(),word.getMsg());//准备起飞
                }else if(2==word.getFlyIndex()){
                    wordView2.prepareFly(word.getFuser().getAvatar(),word.getFuser().getNickname(),word.getMsg());//准备起飞
                }
            }
        };
        managerWordsThread.start();//启动管理线程
    }

    /**
     * 总共两架飞机
     * 检测飞文队列及飞机状态，如有飞文要飞且飞机空闲，则飞文登机，飞机做起飞或飞行状态
     */
    private void checkFly(){
        Message msg=null;
        if(flyWords.size()==0){//没消息
            return;
        }
        if(!wordView1.isFlying()){//1状态为飞行结束
            CommonMsg word=flyWords.get(0);
            word.setFlyIndex(1);
            wordView1.updateState(true);//状态改为起飞/飞行中
            msg=mHandler.obtainMessage();
            msg.what=MAIN_HANDLE_FLY;
            msg.obj=word;
            mHandler.sendMessage(msg);
            flyWords.remove(0);
            return;
        }
        if(!wordView2.isFlying()){//2状态为飞行结束
            CommonMsg word=flyWords.get(0);
            word.setFlyIndex(2);
            wordView2.updateState(true);//状态改为起飞/飞行中
            msg=mHandler.obtainMessage();
            msg.what=MAIN_HANDLE_FLY;
            msg.obj=word;
            mHandler.sendMessage(msg);
            flyWords.remove(0);
        }
    }


    /**
     * 有飞文到达机场，排队侯飞，插入飞文对象到队列
     */
    public void waitFly(CommonMsg flyWord){
        if(animMsgThreadHandler!=null){
            Message msg=animMsgThreadHandler.obtainMessage();
            msg.what= FlyWordThread.HANDLE_WAIT_FLY;
            msg.obj=flyWord;
            animMsgThreadHandler.sendMessage(msg);//插队
        }
    }

    /**
     * 飞行结束
     * @param index
     */
    @Override
    public void onFlyWordAnimEnd(int index) {
        if(animMsgThreadHandler!=null){
            Message msg=animMsgThreadHandler.obtainMessage();
            msg.what= FlyWordThread.HANDLE_END;
            msg.obj=index;
            animMsgThreadHandler.sendMessage(msg);
        }
    }

    public void destroy(){
        if(managerWordsThread!=null){
            managerWordsThread.stopLoop();
        }
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler=null;
        }
        if(wordView1!=null){
            wordView1.destroy();
        }
        if(wordView2!=null){
            wordView2.destroy();
        }
        flyWords.clear();
    }

    class FlyWordThread extends Thread{
        private final static int HANDLE_CHECK_FLY=0x1;//读取飞文，标记飞文视图为正在动画
        public final static int HANDLE_WAIT_FLY=0x2;//信息到达插入排队
        public final static int HANDLE_END=0x3;//更新状态为飞结束
        private Looper mLooper;
        private Timer readMsgTimer=new Timer(true);
        private TimerTask readMsgTask;
        FlyWordThread() {
            readMsgTask=new TimerTask() {
                @Override
                public void run() {
                    if(animMsgThreadHandler!=null){
                        animMsgThreadHandler.sendEmptyMessage(HANDLE_CHECK_FLY);
                    }
                }
            };
        }

        @Override
        public void run() {
            readMsgTimer.schedule(readMsgTask,0,1000);//1秒显示读一次消息
            Looper.prepare();
            mLooper=Looper.myLooper();
            animMsgThreadHandler=new Handler(mLooper){
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what){
                        case HANDLE_CHECK_FLY:
                            checkFly();
                            break;
                        case HANDLE_WAIT_FLY:
                            flyWords.add((CommonMsg)msg.obj);
                            break;
                        case HANDLE_END:
                            int index=(int)msg.obj;
                            //Toast.makeText(getContext(),"重置"+index+"动画",Toast.LENGTH_LONG).show();
                            if(index==1){
                                wordView1.updateState(false);
                            }else{
                                wordView2.updateState(false);
                            }
                            break;
                        default:
                            break;
                    }
                }
            };
            Looper.loop();
        }

        public void stopLoop(){
            if(readMsgTimer!=null){
                readMsgTimer.cancel();
                readMsgTimer=null;
            }
            if(readMsgTask!=null){
                readMsgTask.cancel();
                readMsgTask=null;
            }
            if(animMsgThreadHandler!=null){
                animMsgThreadHandler.removeCallbacksAndMessages(null);
            }
            if(mLooper!=null){
                mLooper.quit();
            }
            animMsgThreadHandler=null;
        }
    }

}
